package com.yh.tea.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yh.tea.entity.Article;
import com.yh.tea.entity.ArticleType;
import com.yh.tea.mapper.ArticleMapper;
import com.yh.tea.model.ArticleQuery;
import com.yh.tea.model.ArticleTypeVO;
import com.yh.tea.model.ArticleVO;
import com.yh.tea.model.PageDTO;
import com.yh.tea.service.ArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yh.tea.service.ArticleTypeService;
import com.yh.tea.utiity.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yh
 * @since 2024-04-07
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Autowired
    private ArticleTypeService articleTypeService;

    @Override
    public ResponseResult getPage(ArticleQuery articleQuery) {
        Page<Article> page= Page.of(articleQuery.getPageNo(),articleQuery.getPageSize());

        // 1.2.排序条件
        if(articleQuery.getSortBy().isEmpty()){
            // 如果排序字段为空，按照更新时间排序
            page.addOrder(new OrderItem("date_issued", false));
        } else {
            page.addOrder(new OrderItem(articleQuery.getSortBy(), articleQuery.getIsAsc()));
        }

        //模糊查询寻
        if(articleQuery.getArticleName().isEmpty()){
            this.page(page);

        }else {
            this.page(page,new QueryWrapper<Article>().like("type_name",articleQuery.getArticleName()));
        }

        List<Article> articleList=page.getRecords();

        if(articleList == null || articleList.isEmpty()){
            return ResponseResult.success("",new PageDTO<ArticleVO>(page.getPages(),page.getTotal(),new ArrayList()));
        }

        // 4. 存在数据，进行实体类转换
        List<ArticleVO> articleVOList=new ArrayList();


        for (Article article : articleList) {
            String articleName= articleTypeService.getOne(new QueryWrapper<ArticleType>().eq("id",article.getType())).getTypeName();
            articleVOList.add(new ArticleVO(article.getTitle(),article.getContent(),articleName,article.getImageurls()));
        }
        // 5. 封装返回结果
        return ResponseResult.success("",new PageDTO<ArticleVO>(page.getTotal(),page.getPages(),articleVOList));
    }
}
